package org.tooyoung.fourone.chat;

import android.content.Intent;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.ui.EaseContactListFragment;
import com.hyphenate.exceptions.HyphenateException;

import org.tooyoung.fourone.R;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ContactListActivity extends AppCompatActivity implements EaseContactListFragment.EaseContactListItemClickListener {

    private EaseContactListFragment fragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_list);

        fragment = new EaseContactListFragment();

        fragment.setContactListItemClickListener(this);

        final Map<String, EaseUser> map = new HashMap<>();

        new Thread(new Runnable() {
            @Override
            public void run() {
                List<String> userNames = null;
                try {
                    userNames = EMClient.getInstance().contactManager().getAllContactsFromServer();
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
                if (userNames != null) {

                    for (String userId : userNames) {
                        map.put(userId, new EaseUser(userId));
                    }
                }
                fragment.setContactsMap(map);
                FragmentManager manager = getSupportFragmentManager();
                FragmentTransaction tx = manager.beginTransaction();
                tx.replace(R.id.ease_container, fragment);
                tx.commit();
            }
        }).start();
    }

    @Override
    public void onListItemClicked(EaseUser user) {
        Intent intent = new Intent(this, ChatActivity.class);
        String userName = user.getUsername();
        intent.putExtra("user", userName);
        startActivity(intent);
    }
}